<template>
  <view class="login-container">
    <uni-forms ref="loginForm" :model="formData" :rules="rules">
      <uni-forms-item name="username">
        <uni-easyinput
          v-model="formData.username"
          placeholder="请输入用户名"
          :clearable="true"
        />
      </uni-forms-item>
      
      <uni-forms-item name="password">
        <uni-easyinput
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          :clearable="true"
        />
      </uni-forms-item>
      
      <button class="submit-btn" @click="handleSubmit">登录</button>
      
      <view class="action-links">
        <navigator url="/pageSign/forget-password" class="link">忘记密码？</navigator>
        <navigator url="/pageSign/sign" class="link">去注册</navigator>
      </view>
      
    </uni-forms>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { FormInstance } from '@dcloudio/uni-ui'

import { useUserStore } from '@/utils/pinia'
import type { UserStore } from '@/utils/pinia'

import { handleLoginIn, LoginInParams } from '@/api/sign'
import { ResponseResult } from '@/utils/request'
const userStore: UserStore = useUserStore()

// 表单数据
const formData = reactive<LoginInParams>({
  username: '',
  password: ''
})

// 表单规则
const rules = {
  username: {
    rules: [
      { required: true, errorMessage: '请输入用户名' },
      { minLength: 3, maxLength: 20, errorMessage: '用户名长度在3-20个字符之间' }
    ]
  },
  password: {
    rules: [
      { required: true, errorMessage: '请输入密码' },
      { minLength: 6, maxLength: 20, errorMessage: '密码长度在6-20个字符之间' }
    ]
  }
}

// 表单实例
const loginForm = ref<FormInstance>()

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await loginForm.value?.validate()
    if (valid) {
      // 登录
      handleLoginIn(formData).then((res: ResponseResult) => {
        console.log(res) 
        if (res && res.status == 1) {
          userStore.login({
            username: formData.username,
            password: formData.password,
            token: res.token
          })
          // 登录成功后跳转到首页
          uni.switchTab({
            url: '/pages/index/index',
            success: () => {
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              })
            }
          })
        }
      })
      
      
    }
  } catch (err) {
    console.error('表单验证失败：', err)
    uni.showToast({
      title: '登录失败',
      icon: 'error'
    })
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  padding: 30rpx;
}

.action-links {
  display: flex;
  justify-content: space-around;
  margin-top: 40rpx;
  
  .link {
    color: #007AFF;
    font-size: 28rpx;
    
    &:active {
      opacity: 0.7;
    }
  }
}
</style>